package com.my.algorithmlearning.leetcode;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName Medium_39_CombinationSum
 * @Description Medium_39_CombinationSum
 * @Author wanghaiwei
 * @Date 2023/2/20 14:30
 */
public class Medium_39_CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> allCombinations = new ArrayList<>();
        subCombination(candidates, 0, target, 0, allCombinations, new ArrayList<Integer>());
        return allCombinations;
    }

    private void subCombination(int[] candidates, int beginIdx, int target, int sum
            , List<List<Integer>> allCombinations, List<Integer> oneCombination) {
        if (target - sum == 0) {
            allCombinations.add(new ArrayList<Integer>(oneCombination));
            return;
        }
        for (int i = beginIdx; i < candidates.length; i++) {
            if (target - sum < candidates[i]) {
                return;
            }
            oneCombination.add(candidates[i]);
            sum += candidates[i];
            subCombination(candidates, i, target, sum, allCombinations, oneCombination);
            oneCombination.remove(oneCombination.size() - 1);
            sum -= candidates[i];
        }
    }

    public static void main(String[] args) {
        Medium_39_CombinationSum solution = new Medium_39_CombinationSum();
        List<List<Integer>> result = solution.combinationSum(new int[]{2, 3, 6, 7}, 7);
        result.forEach(r -> System.out.println(StringUtils.join(r, ',')));
    }
}
